package com.zm.admin.saToken;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.zm.admin.zmeng.domain.ZmMenu;
import com.zm.admin.zmeng.mapper.ZmMenuMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/***
 *
 * @Auther: MuYun
 * @Date: 2022/11/14 17:27
 * @Description： 注册Sa-Token的注解拦截器，打开注解式鉴权功能
 *
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    private static Logger logger= LoggerFactory.getLogger(SaTokenConfig.class);

    @Resource
    private ZmMenuMapper zmMenuMapper;

    // 注册Sa-Token的拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");

        // 注册路由拦截器，自定义认证规则
        registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
            // 权限认证 -- 不同模块认证不同权限
            List<ZmMenu> zmMenus = zmMenuMapper.selectList(null);
            for(ZmMenu zmMenu:zmMenus){
                if(StrUtil.isNotEmpty(zmMenu.getUrl())){
                    SaRouter.match(zmMenu.getUrl(), r -> StpUtil.checkPermissionOr(zmMenu.getPermission()));
                }
            }
            //例：user或admin都可进入
            /*SaRouter.match("/menu/**", r -> StpUtil.checkPermissionOr("user","admin"));
            SaRouter.match("/org/**", r -> StpUtil.checkPermissionOr("user","admin"));
            SaRouter.match("/role/**", r -> StpUtil.checkPermissionOr("user","admin"));
            SaRouter.match("/user/**", r -> StpUtil.checkPermissionOr("user","admin"));*/

        })).excludePathPatterns("/doLogin")
                .excludePathPatterns("/captcha/get").excludePathPatterns("/captcha/check");
        //这个excludePathPatterns是放行
    }

    public static void main(String[] args) {
        String createtime="2022-05-17";
        String[] split = createtime.split("-");
        logger.info("{}",split[0]);
        logger.info("{}",split[1]);
        logger.info("{}",split[2]);

        LocalDate now = LocalDate.now();

        String encryptPassword = SaSecureUtil.aesEncrypt("mi", "minuo7");
        String decryptPwd = SaSecureUtil.aesDecrypt("mi",encryptPassword);

        logger.info("加密后的password:{},解密后的password:{}",encryptPassword,decryptPwd);
    }
}

